//
//  YNetworkViewController.m
//  shijianpinggu
//
//  Created by apple on 2016/12/23.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "YNetworkViewController.h"
#import "YnetworkTableViewCell.h"
#import "YEventViewController.h"
#import "homeModel.h"
#import "YNavigationController.h"

@interface YNetworkViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contViewHeigh;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageHeight;
@property (weak, nonatomic) IBOutlet UILabel *zixunLable;
@property (weak, nonatomic) IBOutlet UILabel *eventL;

@property (weak, nonatomic) IBOutlet UILabel *dangerL;
@property(nonatomic,strong)NSMutableArray *arrayModel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imaHeigh;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIScrollView *ziXunScroll;
@property(nonatomic,assign)CGFloat oldy;

@end

@implementation YNetworkViewController
-(NSMutableArray *)arrayModel{
    if(_arrayModel==nil){
        self.arrayModel = [NSMutableArray arrayWithCapacity:5];
    }
    return _arrayModel;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone; 
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"YnetworkTableViewCell" bundle:nil] forCellReuseIdentifier:@"networkCell"];
    
//    隐藏UINavigationController
    //self.navigationController.navigationBarHidden = YES;
    self.navigationItem.title = @"随身网站监测平台";
    
    NSLog(@"%f",self.view.frame.size.width);
    //self.imaHeigh.constant = 503*self.view.frame.size.width/1080;
    
//    UIImage *image = [UIImage imageNamed:@"index_ban"];
//    self.imageHeight.constant = image.size.height * (self.view.frame.size.width/image.size.width);
    // 设置导航栏背景
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"index_01"] forBarMetrics:UIBarMetricsDefault];
    
    // 设置状态栏
    [UIApplication sharedApplication].statusBarStyle = UIBarStyleBlackOpaque;
    
    [self loadDataFormUrl];
    
    
    self.contViewHeigh.constant = self.view.frame.size.height+20;
    
    
//    if (noticeSize.height>size1.height)
//    {
//        //如果文字大于一行就开始滚动，否则停止timer
//        NSTimer *timer = [[NSTimer alloc] init];
//        timer =  [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(time) userInfo:self repeats:YES];
//        
//    }else{
//        [timer invalidate];
//    }
//    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"gengxin"] ) {
//        [self versionUpdate];
//    }
    

    
}

-(void)viewWillAppear:(BOOL)animated{
    [self loadDataFormUrl];
}
    //滚动的方法
-(void)time{
   
        //oldy用来记录上一次scrollview滚动的位置
        self.ziXunScroll.contentOffset = CGPointMake(_oldy,0);
        if (_oldy>self.zixunLable.frame.size.width) {
            _oldy = 0;
        }else{
            _oldy++;
            
            
            CGPoint position = CGPointMake( _oldy, 0);
            
            [self.ziXunScroll setContentOffset:position animated:YES];

           
    //设置每次滚动的高度，即几个像素
}
    
}
-(void)scrollLabel{
    // 计算尺寸
    CGSize size		 = CGSizeMake(300, 30);
    //self.zixunLable.frame		 = (CGRect){CGPointZero, size};
    
    // 初始化ScrollView
    UIScrollView *showView = self.ziXunScroll;
    showView.contentSize   = size;
    showView.showsHorizontalScrollIndicator = NO;
    
//    
//    // 形成边缘的遮罩
//    UIImageView *imageView = \
//    [[UIImageView alloc] initWithFrame:CGRectMake(0, 90, 320, size.height)];
//    imageView.image = [UIImage imageNamed:@"bg"];
//    [self.view addSubview:imageView];
    
    // 动画
    [UIView animateKeyframesWithDuration:10
                                   delay:7
                                 options:UIViewKeyframeAnimationOptionAllowUserInteraction
                              animations:^{
                                  // 计算移动的距离
                                  CGPoint point = showView.contentOffset;
                                  point.x = size.width - 320.f;
                                  showView.contentOffset = point;
                              }
                              completion:^(BOOL finished) {
                                  
                              }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayModel.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YnetworkTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"networkCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
    homeModel *model = self.arrayModel[indexPath.row];
    
    NSLog(@"%@",self.arrayModel[indexPath.row]);
       // cell.image.image = [UIImage imageNamed:model.imageName];
        cell.nwName.text = model.Sitename;
    
        cell.event.text = [[NSString alloc] initWithFormat:@"%@",model.event ];
        cell.danger.text = [[NSString alloc] initWithFormat:@"%@",model.danger ];
    if (([model.event integerValue] + [model.danger integerValue]) >0) {
        cell.image.image = [UIImage imageNamed:@"yuan_hh"];
    }else{
        
        cell.image.image = [UIImage imageNamed:@"yuan_ll"];
    }
//    if ([model.event integerValue] > 0) {
//        [cell.event setTextColor:[UIColor redColor]];
//    }else{
//        [cell.event setTextColor:[UIColor colorWithRed:31/255.0 green:33/255.0 blue:36/255.0 alpha:1]];
//    }
//    if ([model.danger integerValue] > 0) {
//        [cell.danger setTextColor:[UIColor redColor]];
//    }else{
//        [cell.danger setTextColor:[UIColor colorWithRed:31/255.0 green:33/255.0 blue:36/255.0 alpha:1]];
//    }
     
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60
    ;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YEventViewController *eventVC = [YEventViewController new];
    homeModel *model = self.arrayModel[indexPath.row];
    eventVC.weburl = model.WebUrl;
    eventVC.webid = model.virtual_group_id;
   // self.hidesBottomBarWhenPushed = YES;
    [self showViewController:eventVC sender:nil];
    //self.hidesBottomBarWhenPushed = NO;
}

//请求数据
-(void)loadDataFormUrl{
    
    
    NSDictionary *parameter = @{@"contactid":[[NSUserDefaults standardUserDefaults] stringForKey:@"userid"]};
    
    //    NSLog(@"%@",dict);
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/IndexApp/apiIndex" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"11111111111111%@", dic);
        NSArray *dataAr = dic[@"content"];
         [self.arrayModel removeAllObjects];
        if (dataAr.count != 0) {
            for (NSDictionary *dic in dataAr) {
                NSLog(@"2222222222%@",self.arrayModel);
                
                homeModel *model = [homeModel new];
                [model setValuesForKeysWithDictionary:dic];
                
                
                [self.arrayModel insertObject:model atIndex:0];
            }
            //        冒泡排序
            for(int i = 0;i < [self.arrayModel count]-1;i++){
                for(int j = i+1;j<[self.arrayModel count];j++){
                    homeModel *modeli = self.arrayModel[i];
                    homeModel *modelj = self.arrayModel[j];
                    int numi= [modeli.event intValue] +[modeli.danger intValue];
                    int numj= [modelj.event intValue] +[modelj.danger intValue];
                    
                    if(numi<numj) {
                        //交换
                        [self.arrayModel exchangeObjectAtIndex:i withObjectAtIndex:j];
                        
                    }
                }
            }
            [self.tableView reloadData];
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    
    
    //[self loginUrl];
}
//版本更新
-(void)versionUpdate{
    //获得当前发布的版本
    //    __weak typeof(self) weakSelf=self;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        //        typeof(self) strongSelf=weakSelf;
        // 耗时的操作---获取某个应用在AppStore上的信 息，更改id就行
        NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/lookup?id=1215482078"]
                                                    encoding:NSUTF8StringEncoding error:nil];
        
        if (string!=nil)
        {
            NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            NSString *version = [[[dic objectForKey:@"results"]firstObject]objectForKey:@"version"];
            
            NSString *updateInfo = [[[dic objectForKey:@"results"]firstObject]objectForKey:@"releaseNotes"];
            
            //获得当前版本
            NSString *currentVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
            
            NSLog(@"version-------%@",version);
            NSLog(@"currentVersion--------%@",currentVersion);
            
            
            
            // 更新界面
            
            if ( version &&![version isEqualToString:currentVersion]) {
                //有新版本
                //                    NSString *message = [NSString stringWithFormat:@"%@\n",updateInfo];
                //                    message=@"部分功能修复或升级，为了更好的体验程序，请前往更新";//使用中此行注释
                //                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"有新版本发布啦!" message:message delegate:self cancelButtonTitle:@"忽略" otherButtonTitles:@"前往更新", nil];
                //                [strongSelf willPresentAlertView:alertView];//此方法iOS 7.0之后就不能用
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"有新版本发布啦!" message:@"部分功能修复或升级，为了更好的体验程序，请前往更新" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"更新版本" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
                    NSString *url = @"http://itunes.apple.com/cn/app/id1215482078";
                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
                }];
                UIAlertAction *otherAction1 = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
                }];
                [alertC addAction:otherAction1];
                
                [alertC addAction:otherAction];
                //[[self getCurrentVC] presentViewController:alertC animated:YES completion:nil];
                [self.navigationController showDetailViewController:alertC sender:nil];
            }else{
                //已是最高版本
                //                NSLog(@"已经是最高版本");
            }
            
            
        }
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
